package org.gaaidou.ptarmigan.springboot.functional.service.impl;

import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.gaaidou.ptarmigan.springboot.data.jpa.datasource.DataSourceRouter;
import org.gaaidou.ptarmigan.springboot.functional.constant.DataSourceStrategy;
import org.gaaidou.ptarmigan.springboot.functional.dao.UserDao;
import org.gaaidou.ptarmigan.springboot.functional.service.UserService;
import org.gaaidou.ptarmigan.springboot.functional.vo.UserVo;
import org.gaaidou.ptarmigan.springboot.idworker.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private IdWorker<Long> idWorker;

    @Autowired
    private UserDao userDao;


    @Override
    @Transactional(rollbackOn = Exception.class)
    @DataSourceRouter(DataSourceStrategy.PRIMARY)
    public void add(UserVo userVo) {
        userDao.save(userVo.toUser(idWorker, new Date(), "admin"));

        jdbcTemplate.query("select * from t_user", row -> {
            while (row.next()) {
                log.info("rowId: {}, name: {}", row.getLong(1), row.getString(5));
            }
        });

    }

    @Override
    @Retryable(retryFor = {IllegalStateException.class}, maxAttempts = 5, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public UserVo get(long id) {
        return new UserVo(userDao.findById(id).get());
    }

    @Recover
    public String recover(IllegalStateException e) {
        log.error("recover..., exception: {}", e.getMessage(), e);
        return "SUCCESS";
    }


}
